package run.halo.app.utils.flexmark.ext.pandoc.math.internal;

import com.vladsch.flexmark.html.HtmlWriter;
import com.vladsch.flexmark.html.renderer.NodeRenderer;
import com.vladsch.flexmark.html.renderer.NodeRendererContext;
import com.vladsch.flexmark.html.renderer.NodeRendererFactory;
import com.vladsch.flexmark.html.renderer.NodeRenderingHandler;
import com.vladsch.flexmark.util.html.Attribute;
import com.vladsch.flexmark.util.options.DataHolder;
import run.halo.app.utils.flexmark.ext.pandoc.math.MathBlock;
import run.halo.app.utils.flexmark.ext.pandoc.math.MathInline;

import java.util.HashSet;
import java.util.Set;

public class MathNodeRenderer implements NodeRenderer {
    final MathOptions mOptions;

    public MathNodeRenderer(DataHolder options) {
        this.mOptions = new MathOptions(options);
    }

    @Override
    public Set<NodeRenderingHandler<?>> getNodeRenderingHandlers() {
        Set<NodeRenderingHandler<?>> set = new HashSet<>();
        set.add(new NodeRenderingHandler<>(MathInline.class, this::render));
        set.add(new NodeRenderingHandler<>(MathBlock.class, this::render));

        return set;
    }

    // 行内数学公式渲染
    private void render(MathInline node, NodeRendererContext content, HtmlWriter html) {
        // 添加 <span class="math">
        html.withAttr().attr(Attribute.CLASS_ATTR, mOptions.inlineMathClass).withAttr().tag("span");
        // 添加原文
        html.text(node.getText());
        // 添加 </span>
        html.tag("/span");
    }

    // 数学公式块渲染
    private void render(MathBlock node, NodeRendererContext content, HtmlWriter html) {
        html.withAttr().attr(Attribute.CLASS_ATTR, mOptions.blockMathClass).withAttr().tag("div");
        html.text(node.getOpeningTrailing());
        html.text(node.getChildChars());
        html.text(node.getClosingTrailing());
        html.tag("/div");
    }

    public static class Factory implements NodeRendererFactory {
        @Override
        public NodeRenderer create(DataHolder dataHolder) {
            return new MathNodeRenderer(dataHolder);
        }
    }
}
